import React, { useState, useEffect, useRef } from 'react';
import {
  Card,
  Row,
  Col,
  message,
  Form,
  Checkbox,
  Tabs,
  Space,
  Input,
  InputNumber,
  Button,
  Modal,
  Upload,
} from 'antd';
import {
  AlipayOutlined,
  WechatOutlined,
  MailOutlined,
  PhoneOutlined,
  PlusOutlined,
  ImportOutlined,
  CloseOutlined,
  ExclamationCircleOutlined,
  ExportOutlined,
} from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import CateSelect from '@/components/CategoryComponent';
import ZoneSelect from '@/components/ZoneComponent';
import VendorSelect from '@/components/VendorSelect';
import request from '@/utils/request';
import UploadUtil from '@/components/UploadUtil';
import QuickMenu from '@/components/QuickMenu';

const { TabPane } = Tabs;
const { confirm } = Modal;
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};
const apiURL = '/api/services/app/Vendor/';

const ViewPage: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const [EPay, setEPay] = useState(false);
  const [data, setData] = useState<any>({});
  const formRef = useRef<any>(null);
  const intl = useIntl();
  useEffect(() => {
    // componentDidMount
  }, []);

  const onFinish = (values: any) => {
    const Vendor = values.Vendor;
    Vendor.id = data.id;
    Vendor.vendorNum = data.vendorNum;
    setLoading(true);
    request(apiURL + 'Modify', {
      method: 'POST',
      data: Vendor,
    }).then((response) => {
      if (response) {
        if (response.success) {
          message.success(intl.formatMessage({id:'pages.save.success'}));
        }
        setLoading(false);
      }
    });
  };

  const newObj = () => {
    const value = {
      vendorID: '0',
      name: '0',
      address1: '0',
      termsCode: '0',
    };
    request(apiURL + 'New', {
      method: 'POST',
      data: value,
    }).then((response) => {
      if (response) {
        console.log(response);
        if (response.success) {
          message.success(intl.formatMessage({id:'pages.new.success'}));
          const Vendor = response.result.data;
          getObj(Vendor);
        } else {
          message.error(response.error.message + response.error.details);
        }
        setLoading(false);
      }
    });
  };

  const getObj = (e: any) => {
    if (e.vendorNum) {
      request(apiURL + 'GetByNum', {
        method: 'GET',
        params: { num: e.vendorNum },
      }).then((response) => {
        if (response) {
          if (response.success) {
            if (response.result.success) {
              const data = response.result.data;
              setData(data);
              formRef.current.setFieldsValue({ Vendor: data });
            } else {
              message.error(response.result.message);
            }
          } else {
            message.error(response.error.message);
          }
          setLoading(false);
        }
      });
    }
  };

  const delObj = () => {
    confirm({
      title: intl.formatMessage({id:'pages.warning'}),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({id:'pages.delete.confirm'}),
      onOk() {
        if (data.items != null && data.items.length > 0) {
          message.error(intl.formatMessage({id:'pages.cannotdelete.existPoline'}));
          return;
        }
        request(apiURL + 'Delete', {
          method: 'DELETE',
          params: { id: data.id },
        }).then((response) => {
          if (response) {
            if (response.success) {
              formRef.current.resetFields();
            } else {
              message.error(response.error.message);
            }
          }
        });
      },
    });
  };

  const handlerExport = async () => {
    setLoading(true);
    const resp = await request('/api/Excel/ExportVendor', {
      method: 'POST',
      responseType: 'blob',
    });

    const url = window.URL.createObjectURL(resp);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'vendor.xls';
    a.click();
    setLoading(false);
  };

  const handlerImport = (info: any) => {
    if (info.file.status === 'done') {
      message.success(intl.formatMessage({id:'pages.import.success'}));
      setLoading(false);
    } else {
      setLoading(true);
    }
  };

  return (
    <div>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={newObj}>
            <span>
              <FormattedMessage id="pages.new" />
            </span>
          </Button>
          <Button type="primary" htmlType="submit" loading={loading}>
            <FormattedMessage id="pages.save" />
          </Button>
          <Button
            type="default"
            icon={<ExportOutlined />}
            onClick={handlerExport}
            loading={loading}
          >
            <span>
              <FormattedMessage id="pages.export" />
            </span>
          </Button>
          <Upload
            accept=".xls,.xlsx,application/vnd.ms-excel"
            name="file"
            action="/api/Excel/ImportVendor"
            headers={{
              Authorization: UploadUtil.accessToken,
            }}
            beforeUpload={UploadUtil.checkExcel}
            showUploadList={false}
            onChange={handlerImport}
          >
            <Button icon={<ImportOutlined />} loading={loading}>
              <span>
                <FormattedMessage id="pages.import" />
              </span>
            </Button>
          </Upload>
          <Button danger icon={<CloseOutlined />} onClick={delObj}>
            <span>
              <FormattedMessage id="pages.delete" />
            </span>
          </Button>
          <QuickMenu path="/purchase/vendor" icon="icon-businessman" title="pages.vendor" />
        </Space>
        <Card style={{ marginTop: 8 }}>
          <Tabs defaultActiveKey="1">
            <TabPane tab={<FormattedMessage id="pages.detail" />} key="1">
              <Row gutter={[16, 16]}>
                <Col xs={20} sm={20} md={20} lg={12} xl={12}>
                  <Form.Item label={<FormattedMessage id="pages.vendorNum" />}>
                    <Input.Group compact>
                      <VendorSelect
                        width={200}
                        noStyle
                        name={['Vendor', 'vendorNum']}
                        rules={[
                          {
                            required: true,
                            message: <FormattedMessage id="pages.vendorNum.required" />,
                          },
                        ]}
                        disabled
                        setCurrent={getObj}
                      />
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    name={['Vendor', 'vendorID']}
                    label={<FormattedMessage id="pages.vendorID" />}
                    rules={[{ required: true }]}
                  >
                    <Input style={{ width: 200 }} />
                  </Form.Item>
                  <Form.Item
                    name={['Vendor', 'name']}
                    label={<FormattedMessage id="pages.vendorName" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.vendorName.required" /> },
                    ]}
                  >
                    <Input />
                  </Form.Item>
                  <CateSelect
                    layout="taxRegion"
                    width={200}
                    required={true}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.taxRegion.required" /> },
                    ]}
                    name={['Vendor', 'taxRegionCode']}
                    label={<FormattedMessage id="pages.taxRegion" />}
                  />
                  <CateSelect
                    layout="Terms"
                    width={200}
                    name={['Vendor', 'termsCode']}
                    label={<FormattedMessage id="pages.termsPay" />}
                  />
                  <CateSelect
                    layout="currency"
                    width={200}
                    name={['Vendor', 'currencyCode']}
                    label={<FormattedMessage id="pages.currency" />}
                  />
                  <Form.Item
                    name={['Vendor', 'address1']}
                    label={<FormattedMessage id="pages.address" />}
                    rules={[
                      { required: true, message: <FormattedMessage id="pages.address.required" /> },
                    ]}
                  >
                    <Input.TextArea />
                  </Form.Item>
                </Col>
                <Col xs={20} sm={20} md={20} lg={12} xl={12}>
                  <Form.Item style={{ marginBottom: 0 }} wrapperCol={{ offset: 5 }}>
                    <Input.Group compact>
                      <Form.Item name={['Vendor', 'globalLock']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.globalLock" />
                        </Checkbox>
                      </Form.Item>
                      <Form.Item name={['Vendor', 'globalVendor']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.globalVendor" />
                        </Checkbox>
                      </Form.Item>
                      <Form.Item name={['Vendor', 'approved']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.approved" />
                        </Checkbox>
                      </Form.Item>
                      <Form.Item name={['Vendor', 'inActive']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.invalid" />
                        </Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    name={['Vendor', 'minOrderValue']}
                    label={<FormattedMessage id="pages.minOrderValue" />}
                  >
                    <InputNumber min={0} />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<FormattedMessage id="pages.contactor" />} key="3">
              <Row>
                <Col xs={20} sm={20} md={20} lg={12} xl={12}>
                  <ZoneSelect
                    layout="Zone"
                    width={100}
                    label={<FormattedMessage id="pages.conntryzone" />}
                    name="Vendor"
                  />
                  <Form.Item name={['Vendor', 'email']} label={<FormattedMessage id="pages.email" />}>
                    <Input prefix={<MailOutlined />} />
                  </Form.Item>
                </Col>
                <Col xs={20} sm={20} md={20} lg={12} xl={12}>
                  <Form.Item
                    name={['Vendor', 'contactor']}
                    label={<FormattedMessage id="pages.contactor" />}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    name={['Vendor', 'phoneNum']}
                    label={<FormattedMessage id="pages.telphone" />}
                  >
                    <Input prefix={<PhoneOutlined />} />
                  </Form.Item>
                  <Form.Item name={['Vendor', 'mobile']} label={<FormattedMessage id="pages.mobile" />}>
                    <Input />
                  </Form.Item>
                  <Form.Item name={['Vendor', 'faxNum']} label={<FormattedMessage id="pages.fax" />}>
                    <Input />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
            <TabPane tab={<FormattedMessage id="pages.commentText" />} key="4">
              <Form.Item name={['Vendor', 'commentText']}>
                <Input.TextArea rows={10} />
              </Form.Item>
            </TabPane>
            <TabPane tab={<FormattedMessage id="pages.bankAccount" />} key="5">
              <Row>
                <Col xs={20} sm={20} md={20} lg={12} xl={12}>
                  <Form.Item wrapperCol={{ offset: 5 }} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <Form.Item name={['Vendor', 'ePay']} valuePropName="checked">
                        <Checkbox
                          onChange={(e) => {
                            setEPay(e.target.checked);
                          }}
                        >
                          <FormattedMessage id="pages.epay" />
                        </Checkbox>
                      </Form.Item>
                      <Form.Item name={['Vendor', 'inActive']} valuePropName="checked">
                        <Checkbox>
                          <FormattedMessage id="pages.invalid" />
                        </Checkbox>
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item label={<FormattedMessage id="pages.bank" />} style={{ marginBottom: 0 }}>
                    <Input.Group compact>
                      <Form.Item name={['Vendor', 'bankID']}>
                        <Input placeholder={intl.formatMessage({id:'pages.bankCode'})} disabled={EPay} />
                      </Form.Item>
                      <Form.Item name={['Vendor', 'bankName']}>
                        <Input placeholder={intl.formatMessage({id:'pages.bankName'})} disabled={EPay} />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.bankAccount" />}
                    name={['Vendor', 'bankAcct']}
                  >
                    <Input disabled={EPay} />
                  </Form.Item>
                  <Form.Item
                    label={<FormattedMessage id="pages.alipay" />}
                    name={['Vendor', 'alipayAcct']}
                  >
                    <Input prefix={<AlipayOutlined />} disabled={!EPay} />
                  </Form.Item>
                  <Form.Item label={<FormattedMessage id="pages.wepay" />} name={['Vendor', 'wePayAcct']}>
                    <Input prefix={<WechatOutlined />} disabled={!EPay} />
                  </Form.Item>
                </Col>
              </Row>
            </TabPane>
          </Tabs>
        </Card>
      </Form>
    </div>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewPage);
